package likou;

/**
 * @description:
 * @title: ListNodeDemo
 * @author: zp
 * @date: 2021/11/28 20:54
 */
public class ListNodeDemo {
    public static void main(String[] args) {
        ListNode listNode1=new ListNode(1);
        ListNode listNode2=new ListNode(1);
        ListNode listNode3=new ListNode(2);
        ListNode listNode4=new ListNode(1);
        ListNode listNode5=new ListNode(1);
        listNode1.next=listNode2;
        listNode2.next=listNode3;
        listNode3.next=null;
        listNode4.next=listNode5;
        listNode5.next=null;
        deleteDuplicates(listNode1);
        show(listNode1);
    }
    /**
     * @description: 在链表中删除相同的元素
     * @author: zp
     * @date: 2021/12/1 19:56
     * @param: head
     * @return: likou.ListNode
     */
    public static ListNode deleteDuplicates(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode temp=head;
        ListNode tempNext=head.next;
        ListNode count;

        while (temp != null) {
            count = temp;
            while (tempNext != null && temp.val == tempNext.val) {
                temp = temp.next;
                tempNext = temp.next;
            }
            if (!count.equals(temp)) {
                count.next = temp;
            }

            temp = temp.next;
            if (temp != null) {
                tempNext = temp.next;
            }

        }
        return head;

    }
    /**
     * @description: 显示链表所有元素
     * @author: zp
     * @date: 2021/12/1 19:56
     * @param: head
     * @return: void
     */
    public static void show(ListNode head) {
        if(head==null){
            System.out.println("无数据");
            return;
        }
        ListNode temp=head.next;
        while (temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }
    }

    /**
     * @description: 和并两个有序链表
     * @author: zp
     * @date: 2021/12/1 19:57
     * @param: list1
     * @param: list2
     * @return: likou.ListNode
     */
    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //新定义一个头节点
        ListNode head = new ListNode(-1);
        //定义一个临时变量保存头节点
        ListNode pre=head;
        while (list1!=null && list2!=null){
            //当l1.val < l2.val 把l1的元素加入pre.next 然后l1在指向下一个节点
            if(list1.val<list2.val){
                pre.next=list1;
                list1=list1.next;
            }else {
                //当l1.val > l2.val 把l2的元素加入pre.next 然后l2在指向下一个节点
                pre.next=list2;
                list2=list2.next;
            }
            //如果遍历完成 让pre指向剩余链表的元素
            pre=pre.next;
        }
        //如果其中有一条链表为空 返回另一条
        pre.next=list1==null?list2:list1;
        return head.next;
    }
}